<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			:width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="销售方式" name="saleMethod">
							<a-select
								v-model:value="formData.saleMethod"
								:options="tool.dictList('saleMethod')"
								placeholder="请选择销售方式"
							>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="销售/工程订单" name="saleOrderId">
							<xn-page-selector
								@change="orderSelectChange"
								ref="saleorderRef"
								:field-names="{ label: 'code', value: 'id' }"
								:page-function="(param) => getSaleOrder(param)"
								v-model:value="formData.saleOrderId"
								placeholder="请选择订单"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="销售员" name="salePerName">
							<div @click="selectionParticipants()">
								<a-input readonly v-model:value="formData.salePerName" placeholder="请选择销售员" allow-clear />
							</div>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="付款日期" name="payDate">
							<a-date-picker
								format="YYYY-MM-DD"
								placeholder="请选择付款日期"
								style="width: 100%"
								v-model:value="formData.payDate"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="收货人手机号" name="phone">
							<a-input v-model:value="formData.phone" placeholder="请输入收货人手机号" allow-clear />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="收货人地址" name="address">
							<a-input v-model:value="formData.address" placeholder="请输入收货人地址" allow-clear />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="备注" name="remark">
							<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="24">
						<a-row>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-row>

						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.saleSheetDetailAddParamList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>

								<template v-if="column.dataIndex === 'warehouseId'">
									<a-select
										:getPopupContainer="(trigger) => trigger.parentNode"
										v-model:value="record.warehouseId"
										placeholder="请选择发货仓库"
									>
										<a-select-option v-for="item in warehouseList" :key="item.id" :value="item.id">{{
											item.warehouseName
										}}</a-select-option>
									</a-select>
								</template>

								<template v-if="column.dataIndex === 'saleNum'">
									<a-input v-if="engineerOrder" disabled :style="{ width: column.width }" defaultValue="0" />
									<a-input v-else disabled :style="{ width: column.width }" v-model:value="record.saleNum" />
								</template>

								<template v-if="column.dataIndex === 'outNum'">
									<a-input
										:style="{ width: column.width }"
										v-model:value="record.outNum"
										@input="outNumChange(record)"
									/>
								</template>
								<template v-if="column.dataIndex === 'remark'">
									<a-input :style="{ width: column.width }" v-model:value="record.remark" />
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>

				<div style="margin-top: 15px">
					<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
				</div>
				<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>出库数量:</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="saleNum" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>不含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
		<user-selector-plus
			ref="userSelectorPlusRef"
			:org-tree-api="selectorApiFunction.orgTreeApi"
			:user-page-api="selectorApiFunction.userPageApi"
			:checked-user-list-api="selectorApiFunction.checkedUserListApi"
			:data-is-converter-flw="true"
			@onBack="selectUserCallback"
		/>
	</div>
</template>

<script setup name="salesOutboundInfo">
	import { required, rules } from '@/utils/formRules'
	import productSelector from '@/components/Selector/productSelector.vue'
	import { message } from 'ant-design-vue'
	import { toRaw } from 'vue'
	import storeCenterApi from '@/api/base_data/storeCenterApi'
	import bizPositionApi from '@/api/biz/bizPositionApi'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import orgApi from '@/api/sys/orgApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import saleorderApi from '@/api/sale/order/saleorderApi'
	import salesheetApi from '@/api/sale/salesheetApi'
	import saleorderdetailApi from '@/api/sale/order/saleorderdetailApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import dayjs from 'dayjs'
	import tool from '@/utils/tool'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const productsRef = ref()
	const formRef = ref()
	const warehouseList = ref([])
	const saleorderRef = ref()
	const engineerOrder = ref(false)

	const selectOrderItem = ref()

	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const saleNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)
	const userSelectorPlusRef = ref()
	const selectorApiFunction = {
		orgTreeApi: (param) => {
			return orgApi.orgOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		userPageApi: (param) => {
			return orgApi.orgUserSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		checkedUserListApi: (param) => {
			return userCenterApi.userCenterGetUserListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}

	const getSaleOrder = (param) => {
		return new Promise((resolve, rejected) => {
			saleorderApi
				.getPage(param)
				.then((res) => {
					// res.records.forEach((it) => {
					// 	if (it.type == '销售') {
					// 		it['label'] = it['contractName']
					// 	} else {
					// 		it['label'] = it['proName']
					// 	}
					// })
					resolve(res)
				})
				.catch((e) => {
					rejected(e)
				})
		})
	}

	const orderSelectChange = (value, array) => {
		engineerOrder.value = array.type == '工程'
		selectOrderItem.value = array
		formData.value.saleSheetDetailAddParamList = []
	}

	const selectionParticipants = () => {
		let data = []
		if (formData.value.salePerId) {
			data.push({
				key: 'USER',
				label: formData.value.acceptPerName,
				value: formData.value.acceptPerId
			})
		}
		userSelectorPlusRef.value.showUserPlusModal(data)
	}

	const selectUserCallback = (value) => {
		formData.value.salePerId = value.value
		formData.value.salePerName = value.label
	}

	const treeData = ref([])

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {}
		if (record) {
			let params = { ...record }
			params.payDate = ref(dayjs(params.payDate))
			saleNum.value = record.saleNum
			noTaxAmount.value = record.noTaxAmount
			taxAmount.value = record.taxAmount
			formData.value = { ...params }
			loadDetail(record)
		} else {
			formData.value.payDate = ref(dayjs())
		}
		bizPositionApi.positionOrgTreeSelector().then((res) => {
			treeData.value = res
		})
		nextTick(() => {
			saleorderRef.value.onPage({})
		})
		storeCenterApi
			.getPage({
				current: 1,
				size: 1000
			})
			.then((res) => {
				warehouseList.value = res.records
			})
			.catch(() => {})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const outNumChange = (record) => {
		let value = record.outNum.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.outNum = ''
		} else {
			record.outNum = value
		}
		let outNum = parseInt(record.outNum) || 0
		let itemSaleNum = parseInt(record.saleNum) || 0
		if (outNum > itemSaleNum) {
			record.outNum = itemSaleNum
			record.remainingQuantity = '0'
		} else {
			record.remainingQuantity = itemSaleNum - outNum
		}
		saleNum.value = totalOrderNum()
	}

	const taxRateChange = (record) => {
		let value = record.taxRate.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.taxRate = ''
		} else {
			record.taxRate = value
		}
	}
	const totalExcludingTaxTax = () => {
		let orderList = formData.value.saleSheetDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.saleSheetDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.saleSheetDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let outNum = it['outNum']
			if (outNum) {
				amount += parseInt(outNum)
			}
		})
		return amount
	}

	const removeGoods = () => {
		let datas = formData.value.saleSheetDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['id'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		saleNum.value = totalOrderNum()
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const onProductChange = (items) => {
		let saleSheetDetailAddParamList = formData.value.saleSheetDetailAddParamList || []
		items.forEach((it) => {
			if (!it['remainingQuantity']) {
				it['remainingQuantity'] = it['saleNum']
			}
			if (!it['outNum']) {
				it['outNum'] = ''
			}
			let find = saleSheetDetailAddParamList.find((item) => {
				return item['key'] == it['key']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.saleSheetDetailAddParamList = items
		saleNum.value = totalOrderNum()
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		payDate: [required('请选择付款日期')],
		saleMethod: [required('请选择销售方式')],
		saleOrderId: [required('请选择订单')],
		settleMethod: [required('请选择结算方式')],
		salePerName: [required('请选择销售员')],
		phone: [required('请输入收货人手机号'), rules.phone],
		address: [required('请输入收货人地址')]
	}

	const addProduct = () => {
		if (!formData.value.saleOrderId) {
			message.error('请选择订单!')
			return
		}
		if (!formData.value.saleSheetDetailAddParamList) {
			formData.value.saleSheetDetailAddParamList = []
		}
		console.log(formData.value.saleSheetDetailAddParamList)
		productsRef.value.showDialog(formData.value.saleSheetDetailAddParamList)
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.saleSheetDetailAddParamList) || []
				if (orderList.length <= 0) {
					message.error('请添加商品')
					return
				}
				let msg = null
				let itemRules = [
					{
						field: 'warehouseId',
						error: '发货仓库不能为空!'
					},
					{
						field: 'outNum',
						error: '出库数量不能为空!'
					}
				]
				for (let i = 0; i < orderList.length; i++) {
					for (let rule of itemRules) {
						let item = orderList[i]
						let itemValue = item[rule['field']]
						if (!itemValue) {
							msg = `第${i + 1}行${rule['error']}`
							break
						}
					}
				}
				if (msg) {
					message.error(msg)
					return
				}
				submitLoading.value = true
				let params = { ...formData.value }
				if (params.id) {
					params.saleSheetDetailEditParamList = [].concat(orderList)
					params.saleSheetDetailAddParamList = null
				} else {
					params.saleSheetDetailAddParamList = orderList
				}
				let formatrePayDate = params.payDate.format('YYYY-MM-DD HH:mm:ss')
				salesheetApi
					.addOrEdit(
						Object.assign(params, {
							saleNum: saleNum.value,
							taxAmount: taxAmount.value,
							noTaxAmount: noTaxAmount.value,
							payDate: formatrePayDate
						})
					)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.catch(() => {})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const loadDetail = (record) => {
		salesheetApi
			.detail({
				id: record.id
			})
			.then((res) => {
				let detailList = res.proSaleSheetDetailList
				detailList.forEach((it) => {
					it['id'] = it['materialId'] || it['productId']
					it['key'] = it['materialId'] || it['productId']
				})
				formData.value.saleSheetDetailAddParamList = detailList
			})
			.catch(() => {})
	}

	const getOrderDetailList = (parameter) => {
		return saleorderdetailApi
			.getPage(
				Object.assign(parameter, {
					saleId: formData.value.saleOrderId
				})
			)
			.then((res) => {
				res.records.forEach((it) => {
					it['saleDetailId'] = it['id']
					it['key'] = it['materialId'] || it['productId']
					it['id'] = it['materialId'] || it['productId']
					it['remark'] = ''
				})
				return res
			})
			.catch(() => {})
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.code || record.productCode
			}
		},
		{
			title: '名称',
			width: 120,
			dataIndex: 'name',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.materialName || record.productName
			}
		},

		{
			title: '单位',
			width: 100,
			dataIndex: 'unit',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.unit || record.productUnit
			}
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.spec || record.productSpec
			}
		},
		{
			title: '单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.code || record.productCode
			}
		},
		{
			title: '名称',
			dataIndex: 'name',
			width: 180,
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => {
				return record.materialName || record.productName
			}
		},
		{
			title: '发货仓库',
			width: 160,
			dataIndex: 'warehouseId',
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 100,
			align: 'center',
			customRender: ({ record }) => {
				return record.unit || record.productUnit
			}
		},
		{
			title: '规格',
			dataIndex: 'spec',
			width: 120,
			align: 'center',
			customRender: ({ record }) => {
				return record.spec || record.productSpec
			}
		},
		{
			title: '价格',
			dataIndex: 'price',
			width: 120,
			align: 'center'
		},
		{
			title: '销售数量',
			dataIndex: 'saleNum',
			width: 120,
			align: 'center'
		},
		{
			title: '税率',
			dataIndex: 'taxRate',
			width: 120,
			align: 'center'
		},
		{
			title: '剩余出库数量',
			dataIndex: 'remainingQuantity',
			width: 120,
			align: 'center'
		},
		{
			title: '出库数量',
			dataIndex: 'outNum',
			width: 120,
			align: 'center'
		},

		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
